from django.conf import settings
from django.shortcuts import render_to_response
from django import forms
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect,HttpResponseNotFound
from django.template import RequestContext,loader
from django.contrib.auth.decorators import login_required,user_passes_test
from django.utils.translation import gettext_lazy as _

from pacs.models import Contest,ContestName,Task
from forms_admin import AddContestManipulator

@user_passes_test(lambda u: u.has_perm("pacs.add_contest") and u.has_perm("pacs.add_contest_name"))
def add_contest(request):

	c = RequestContext(request)
	manipulator = AddContestManipulator()
	if request.POST:
		data = request.POST.copy()
		data.update(request.FILES)
		errors = manipulator.get_validation_errors(data)
		if not errors:
				manipulator.do_html2python(data)
				contest = Contest(startTime=data['startTime'],slug=data['slug'])
				contest.save()
				contestName = ContestName(contest=contest,lang=settings.LANGUAGE_CODE[:2],name=data['name'])
				contestName.save()
				return HttpResponseRedirect(reverse('pacs.views.show_contest',None,(),{'contest_id':contest.id}))
	else:
		from datetime import datetime
		now = datetime.now()
		def cut_milis(s):
			return s[:s.find('.')]
		data = {'startTime':cut_milis(now.isoformat(' '))}
		errors = {}
	c['form'] = forms.FormWrapper(manipulator,data,errors)
	return render_to_response('pacs/add_contest.xhtml', c)

@user_passes_test(lambda u: u.has_perm("pacs.contest"))
def add_task_to_contest(request,contest_id,task_slug):

	c = RequestContext(request)
	try:
		contest = Contest.objects.get(id=int(contest_id))
	except Contest.DoesNotExist:
		c['what'] = _('Contest')
		return HttpResponseNotFound(loader.get_template('404.xhtml').render(c))
	try:
		task = Task.objects.get(slug=task_slug)
	except Task.DoesNotExist:
		c['what'] = _('Task')
		return HttpResponseNotFound(loader.get_template('404.xhtml').render(c))
	contest.tasks.add(task)
	return HttpResponseRedirect(reverse('pacs.views.show_contest',None,(),{'contest_id':contest.id}))
